import { _decorator, Component, Node, RigidBody2D, Sprite, SpriteFrame, UITransform } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Background')
export class Background extends Component {
    @property({type:Node})
    private player:Node = null

    @property({type:Number})
    layer:number = 0

    @property({type:[SpriteFrame]})
    spriteFrames:SpriteFrame[] = []

    s:number = 0

    private playerlvx:number = 0

    start() {

    }

    getRandomInt(min: number, max: number): number {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    update(deltaTime: number) {

        this.playerlvx = this.player.getComponent(RigidBody2D).linearVelocity.x

        if(this.playerlvx>1){
            this.s = this.layer/5*this.playerlvx/10
        }else if(this.playerlvx<-1){
            this.s = -this.layer/5*this.playerlvx/10
        }else{
            this.s = 0
        }
        this.node.setPosition(this.node.position.x + this.s,this.node.position.y,0)
        if(this.player.position.x -  this.node.position.x > this.node.getComponent(UITransform).contentSize.x){
            this.node.setPosition(this.node.position.x + (this.node.getComponent(UITransform).contentSize.x*2),this.node.position.y,0)
            //替换背景图片
            this.node.getComponent(Sprite).spriteFrame = this.spriteFrames[this.getRandomInt(0,this.spriteFrames.length-1)]
        }
    }
}


